package com.losdun.weixin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.losdun.weixin.common.WxConstants;
import com.losdun.weixin.domain.WechatUser;
import com.losdun.weixin.mapper.WechatUserMapper;
import com.losdun.weixin.service.WechatUserService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description
 * @Author Sword.Ye
 * @Date 2025/8/18
 **/
@Service
public class WechatUserServiceImpl extends ServiceImpl<WechatUserMapper, WechatUser> implements WechatUserService {
    @Override
    public List<WechatUser> selectWechatUserList(WechatUser wechatUser) {
        return baseMapper.selectList(new QueryWrapper<>(wechatUser));
    }

    @Override
    public WechatUser getWechatUserByOpenId(String openId) {
        LambdaQueryWrapper<WechatUser> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(WechatUser::getOpenId, openId);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public boolean checkPhoneExists(String phoneNumber, String openId) {
        LambdaQueryWrapper<WechatUser> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(WechatUser::getPhone, phoneNumber).ne(WechatUser::getOpenId, openId);
        return baseMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public WechatUser createWxUser(String openId) {
        WechatUser user = getWechatUserByOpenId(openId);
        if(user!=null){
            throw new RuntimeException("用户已存在!");
        }
        user = new WechatUser();
        user.setOpenId(openId);
        user.setUserType(WxConstants.WX_USER_TYPE_MINI);
        user.setCreateTime(LocalDateTime.now());
        baseMapper.insert(user);
        return user;
    }

    @Override
    public void bindPhone(String openId, String phoneNumber) {
        WechatUser user = getWechatUserByOpenId(openId);
        if(user==null){
            throw new RuntimeException("用户不存在!");
        }
        user.setPhone(phoneNumber);
        user.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(user);
    }
}
